﻿App.InstfeeBack = function() {

    return {

        currentFormValues: {},

        getTopStore: function() {
            var store = new Ext.data.Store({
                autoLoad:true,
				baseParams : {start:0, limit:25},
				proxy: new Ext.data.HttpProxy({
					url : 'cost/institems'
				}),
                remoteSort: false,
				reader: new Ext.data.JsonReader({
					totalProperty : 'totalCount',
					root : 'rows',
					idProperty : 'object_id',
					fields: [{
						name: 'inst_id',
						type: 'string'
					},{
						name: 'objid',
						type: 'string'
					},
					{
						name: 'obj_name',
						allowBlank: false
					},
					{
						name: 'obj_num',
						allowBlank: false
					},
					{
						name: 'inst_fee',
						allowBlank: false
					},
					{
						name: 't_inst_fee',
						allowBlank: false
					},
					{
						name:'cost_type'
					}]
				})
            });
            return store;
        },

        getForm: function() {
                var getCostTypeStore = new Ext.data.Store({
                    autoLoad:false,
    				baseParams : {parent_id:1},//1表示direct表id为1的记录(次store取出parent为1的所有记录)
    				proxy: new Ext.data.HttpProxy({
    					url : 'menu/costype'
    				}),
                    remoteSort: false,
    				reader: new Ext.data.JsonReader({
    					totalProperty : 'totalCount',
    					root : 'rows',
    					idProperty : 'id',
    					fields: [{
    						name: 'name',
    						type:'string'
    					},{
    						name: 'id',
    						type: 'string'
    					}]
    				})
                });
               
        	var transitStore = new Ext.data.Store({
            	autoLoad:false,
//				baseParams:{start:0, limit:23},
				proxy: new Ext.data.HttpProxy({
					url : 'transit/items'
				}),
                remoteSort: false,
                reader: new Ext.data.JsonReader({
					totalProperty : 'totalCount',
					root : 'rows',
					idProperty : 'transit_id',
					fields: [{
						name: 'transit_id',
						type: 'string'
					},
					{
						name: 'name',
						type: 'string'
					}]
				})
            });
            var frm = new Ext.form.FormPanel({
            	url:'cost/instmanager',
                labelAlign: 'right',
                frame: true,
                waitMsgTarget:true,
                defaults:{allowBlank :false},
                defaultType: 'textfield',
                items: [
                        {
                        	xtype:"hidden",
                        	name:'inst_id'
                        },
                        {
                        	name: 'objid',
                        	readOnly:true,
                            fieldLabel: '货号'
                        },{
                        	name: 't_inst_fee',
                        	xtype:'numberfield',
                            fieldLabel: '实收'
                        },{
                        	name: 'pay_rat',
                            fieldLabel: '费率',
                            regex:/^\d+(\.\d{1,2})?%$/,
                            regexText:"只能输入类似于50.00%的格式(只包含两位小数)",
                            msgTarget:'under',
                            value:"0.2%",
                            enableKeyEvents:true,
                            listeners : {
                        		change : function(){
		                        	var feilv = this.getValue().trim();
		            				this.setValue(feilv);//去掉空格
                        			if(this.validate()){
                        				if(feilv!=''){
                        					if(feilv.indexOf('%')==-1){
                        						Ext.Msg.alert('提示', '输入有误,没有%!');
                        						return;
                        					}
                        					var feilvformat =parseFloat(feilv.substring(0,feilv.indexOf('%')))/100;
                        					var shishou = parseFloat(this.findParentByType('form').getForm().findField('t_inst_fee').getValue());
                        					var koujian = Number(feilvformat*shishou).toFixed(2);//扣减的费用
                        					if( koujian <2 )
                    						{
                    							koujian=2;
                    						}
                        					this.findParentByType('form').getForm().findField('deduct').setValue(koujian);
                        					var yingfu = shishou - koujian;//应付的费用
                        					this.findParentByType('form').getForm().findField('sh_pay').setValue(yingfu);
                        				}
                        			}
	                        	}
                        	}
                            
                        },{
                        	name: 'sh_pay',
                        	readOnly:true,
                            fieldLabel: '应付'
                        },{
                        	name: 'deduct',
                        	readOnly:true,
                            fieldLabel: '扣减'
                        },{
                        	name: 're_pay',
                        	readOnly:true,
                            fieldLabel: '实付'
                        },{
                        	xtype: 'radiogroup', 
                            fieldLabel: '是否结清',
                            items : [
                                     {
                    					boxLabel: '是',
                    					name: 'settle',
                    					inputValue:1,
                    					checked : true
                                     },
                                     {
                                         boxLabel: '否',
                                         name: 'settle',
                                         inputValue:0
                                     }
                                  ] 
                        }], 
            buttons: [{
                    text: '确定',
                    scope: this,
                    handler: function() {
                        this.submit();
                    }
                },
                {
                    text: '重置',
                    scope: this,
                    handler: function() {
                        var f = this.form.getForm();
                        f.reset();
                        f.setValues(this.currentFormValues);
                        f.clearInvalid();
                    }
                }]
            }); //FormPanel
            return frm;
        },

        submit: function() {
            if (this.form.form.isValid()) {
				this.form.getForm().submit({
                    waitTitle: '保存数据',
                    waitMsg: '正在保存……',
                    scope: this,
                    method: 'post',
                    params: '',
                    success: function(form, action) {
                        var info = action.result.info;
                        if (action.result.success) {
                            this.store.reload();
                            this.lowerGrid.getStore().reload();
                                this.dlg.hide();
                        }
                        Ext.Msg.alert('信息', info);
                    },
                    failure: function(form, action) {
                        var info = action.result.info;
	    				Ext.Msg.alert('提示', info);
                    }
                });
            }
        },

        getDialog: function() {
            var dlg = new Ext.Window({
                width: 550,
                height: 350,
                title: '',
                plain: true,
                closable: true,
                resizable: false,
                frame: true,
                layout: 'fit',
                closeAction: 'hide',
                border: false,
                modal: true,
                items: [this.form],
                listeners: {
                    scope: this,
                    render: function(fp) {
                        this.form.form.waitMsgTarget = fp.getEl();
                    },
                    show: function() {
                        this.form.form.setValues(this.currentFormValues);
                        this.form.form.clearInvalid();
                        if(!this.form.getForm().findField('pay_rat').validate()){
                        	return;
                        }
                        var feilv = this.form.getForm().findField('pay_rat').getValue().trim();
                        var feilvformat =parseFloat(feilv.substring(0,feilv.indexOf('%')))/100;
    					var shishou = parseFloat(this.form.getForm().findField('t_inst_fee').getValue());
    					var koujian = Number(feilvformat*shishou).toFixed(2);//扣减的费用
    					if( koujian <2 )
						{
							koujian=2;
						}
    					this.form.getForm().findField('deduct').setValue(koujian);
    					var yingfu = shishou - koujian;//应付的费用
    					this.form.getForm().findField('sh_pay').setValue(yingfu);
                    }
                }
            }); //dlg
            return dlg;
        },
        highLight: function(value) {
        	var key = App.InstfeeBack.store.baseParams.query;
        	var v = value ? value.toString() : '';
        	if (Ext.isString(v) & Ext.isString(key)) {
        		if (key.length > 0) {
        			var re = new RegExp(key, "g");
        			return v.replace(re, "<span style='color:red;background-color:yellow;'>" + key + "</span>");
        		} else {
        			return v;
        		}
        	} else {
        		return v;
        	}
        },
        dateformate: function(value) {
        	return value.format("Y-m-d h:i:s");
        },
        createGrid: function(id) {

            var panel = Ext.getCmp(id);

            panel.body.dom.innerHTML = "";
            this.gird = this.getTopGrid();
            this.lowerGrid=this.getLowerGird();
            panel.add(this.gird);
            panel.add(this.lowerGrid);
            
        },
        getTopGrid: function (){
        	
        	var sm = new Ext.grid.CheckboxSelectionModel();
            var topGrid = new Ext.grid.GridPanel({
                tbar: new Ext.PagingToolbar({
                    pageSize: 23,
                    displayInfo: true,
                    store: this.store,
                    items: ['-', 
                            {
                        text: '代收回款',
                        scope: this,
                        handler: function(){
	                    	if(this.gird.getSelectionModel().hasSelection()){
	                    		var selectdata = this.gird.getSelectionModel().getSelected().data;
		                    	Ext.apply(this.currentFormValues, {
		                    		inst_id:selectdata.inst_id,
		                    		objid:selectdata.objid,
		                    		t_inst_fee:selectdata.t_inst_fee
		                    		
		                       });
		                    	this.add("代收回款",this.form, 600, 300);
	                		}else{
	                			Ext.Msg.alert('提示','请选择回款项');
	                		}
                    	}
                    },
                    '-', new Ext.ux.form.SearchField({
                        store: this.store,
                        width: 110
                    })]
                }),
                anchor:'top 50%',
                store: this.store,
                sm: sm,
                loadMask: true,
                autoHeight:true,
                plugins: [Ext.ux.plugins.Print],//打印按钮
                viewConfig : {autoFill:false,forceFit:true},
                columns: [sm,new Ext.grid.RowNumberer(), 
                          {
                			hidden:true,
                			header:"代收ID",
                			dataIndex:'inst_id'
                          },{
                    header: "货号",
                    width: 60,
                    sortable: true,
                    dataIndex: 'objid',
                    renderer: this.highLight
                },{
                    header: "货物名称",
                    width: 60,
                    sortable: true,
                    dataIndex: 'obj_name',
                    renderer: this.highLight
                },{
                    header: "件数",
                    width: 60,
                    sortable: true,
                    dataIndex: 'obj_num',
                    renderer: this.highLight
                },
                {
                	header: "付款方式",
                    width: 150,
                    sortable: true,
                    dataIndex: 'cost_type'
                },{
                    header: "应收",
                    width: 60,
                    sortable: true,
                    dataIndex: 'inst_fee',
                    renderer: this.highLight
                },{
                    header: "实收",
                    width: 60,
                    sortable: true,
                    dataIndex: 't_inst_fee',
                    renderer: this.highLight
                }]
            });
            return topGrid;
        },
        getLowerGird: function(){
        	var lowerStore = new Ext.data.Store({
                autoLoad:true,
				baseParams : {start:0, limit:25},
				proxy: new Ext.data.HttpProxy({
					url : 'cost/isntitems_o'
				}),
                remoteSort: false,
				reader: new Ext.data.JsonReader({
					totalProperty : 'totalCount',
					root : 'rows',
					idProperty : 'object_id',
					fields: [
					{
						name: 'objid',
						type: 'string'
					},
					{
						name: "op_time",
						type: 'date',
						dateFormat: 'time'
					},
					{
						name: "obj_name",
						type:'string'
					},
					{
						name: "obj_num",
						type:'string'
					},
					{
						name: "inst_fee",
						type:'string'
					},
					{
						name: "t_inst_fee",
						type:'string'
					},
					{
						name: "pay_rat",
						type:'string'
					},
					{
						name: "sh_pay",
						type:'string'
					},
					{
						name: "re_pay",
						type:'string'
					}]
				})
            });
        	var sm = new Ext.grid.CheckboxSelectionModel();
            var lowerGird = new Ext.grid.GridPanel({
            	anchor:'-0 50%',
            	width:"100%",
                loadMask: true,
                ref:"lowerGird",
                autoHeight:true,
                plugins: [Ext.ux.plugins.Print],//打印按钮
                viewConfig : {autoFill:false,forceFit:true},
                tbar: new Ext.PagingToolbar({ 
                	pageSize: 25 ,//分页必须加的参数.最好和store里面的limit保持一致
                	displayInfo: true,
                    store: lowerStore,
                    items:[
	               '-', new Ext.ux.form.SearchField({
                    store: lowerStore,
                    width: 110
                })]}),
                store: lowerStore,
                sm: sm,
                columns: [new Ext.grid.RowNumberer(), {
                    header: "货号",
                    width: 100,
                    sortable: true,
                    dataIndex: 'objid',
                    renderer: this.highLight
                },{
                    header: "货名",
                    width: 100,
                    sortable: true,
                    dataIndex: 'obj_name',
                    renderer: this.highLight
                },{
                    header: "件数",
                    width: 100,
                    sortable: true,
                    dataIndex: 'obj_num',
                    renderer: this.highLight
                },{
                    header: "应收",
                    width: 100,
                    sortable: true,
                    dataIndex: 'inst_fee',
                    renderer: this.highLight
                },{
                    header: "实收",
                    width: 100,
                    sortable: true,
                    dataIndex: 't_inst_fee',
                    renderer: this.highLight
                },{
                    header: "费率",
                    width: 100,
                    sortable: true,
                    dataIndex: 'pay_rat',
                    renderer: this.highLight
                },{
                    header: "应付",
                    width: 100,
                    sortable: true,
                    dataIndex: 'sh_pay',
                    renderer: this.highLight
                },{
                    header: "实付",
                    width: 100,
                    sortable: true,
                    dataIndex: 're_pay',
                    renderer: this.highLight
                },{
                    header: "结清",
                    width: 100,
                    sortable: true,
                    dataIndex: 'settle',
                    renderer: this.highLight
                },
                {
                    header: "时间",
                    width: 150,
                    sortable: true,
                    dataIndex: 'op_time',
                    renderer: Ext.util.Format.dateRenderer('Y-m-d H:i:s')
                }]
            });
            return lowerGird;
        },
        save:function(ids,logistics_id,wingrid,lowergrid){
        	Ext.Ajax.request({
				method:'post',
				url:"product/savelogobj",
				params:{
					ids:ids,
					logistics_id:logistics_id
				},
				success: function(resp, opts) {
					var result = Ext.util.JSON.decode(resp.responseText);
					var info = result.info;
					if(result.success=='true') {
						Ext.Msg.alert('信息', info);
						wingrid.store.reload();//刷新弹出窗口数据
						lowergrid.store.reload();//刷新lowergrid
					}else {
                        Ext.Msg.alert('信息', info);
                    }
				},
				failure: function(resp,opts) {
					var result = Ext.util.JSON.decode(resp.responseText);
					var info = result.info;
					Ext.Msg.alert('提示', info); 
				}
			});
        },
        add: function(tile,cmp,width,height) {
//        	this.dlg.removeAll(true);
        	this.dlg.setTitle(tile);
//        	this.dlg.setSize(width,height);
//        	this.dlg.add(cmp);
        	this.dlg.show();
        },

        render: function(id) {
            if (!this.store) {
                this.store = this.getTopStore();
            }; //if(!this.store)
            if (!this.form) {
                this.form = this.getForm();
            }; //if(!this.form)

            if (!this.dlg) {
                this.dlg = this.getDialog();
            }; //if(!this.dlg)
            this.createGrid(id);
        }

    }; //return
} ();
